import { searchSongs, type Song, getAllSongs } from '../../utils/api';
import { toggleFavorite as toggleFav, getFavorites, getHistory } from '../../utils/storage';

Component({
  data: {
    keyword: '',
    results: [] as Song[],
    loading: false,
    searched: false,
    favIds: new Set<string>(),
    recommendTags: ['流行', '摇滚', '民谣', '电子', '爵士', '古典', 'R&B', '嘻哈', '轻音乐', '华语'],
    pageType: 'search', // search, favorites, history
    pageTitle: '搜索',
    showSearch: true
  },
  lifetimes: {
    attached() {
      const fav = getFavorites();
      this.setData({ favIds: new Set(fav.map(s => s.id)) });
      
      const query = this.getPageQuery();
      if (query.type === 'favorites') {
        const favorites = getFavorites();
        const results = favorites.map(s => ({ ...s, liked: true }));
        this.setData({ 
          pageType: 'favorites',
          pageTitle: query.title || '我的收藏',
          results: results,
          showSearch: false
        });
      } else if (query.type === 'history') {
        const history = getHistory();
        const favIds = new Set(getFavorites().map(s => s.id));
        const results = history.map(s => ({ ...s, liked: favIds.has(s.id) }));
        this.setData({ 
          pageType: 'history',
          pageTitle: query.title || '播放历史',
          results: results,
          showSearch: false
        });
      }
    }
  },
  methods: {
    getPageQuery(): any {
      // @ts-ignore
      const pages = getCurrentPages();
      const current = pages[pages.length - 1];
      return (current as any).options || {};
    },
    
    onInput(e: any) {
      this.setData({ keyword: e.detail.value });
    },
    async onSearchTap() {
      await this.performSearch();
    },
    async onSearchConfirm() {
      await this.performSearch();
    },
    async performSearch() {
      const k = this.data.keyword.trim();
      if (!k) { this.setData({ searched: true, results: [] }); return; }
      this.setData({ loading: true });
      const res = await searchSongs(k);
      const results = res.map(s => ({ ...s, liked: this.data.favIds.has(s.id) }));
      this.setData({ results, loading: false, searched: true });
    },
    onPlay(e: any) {
      const song: Song = e.detail.song;
      wx.navigateTo({ url: `/pages/player/index?id=${song.id}` });
    },
    onToggleLike(e: any) {
      const song: Song = e.detail.song;
      const nextFav = toggleFav(song);
      const favIds = new Set(nextFav.map(s => s.id));
      const results = this.data.results.map(s => ({ ...s, liked: favIds.has(s.id) }));
      this.setData({ favIds, results });
    },
    
    onTagTap(e: any) {
      const keyword = e.currentTarget.dataset.keyword;
      this.setData({ keyword });
      this.performSearch();
    }
  }
});